package com.xzkingdee.demo.util;


import com.xzkingdee.demo.model.Record;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TXTUtil {

    public static final String DONE ="./db/done.txt";

    public static final String WORKING ="./db/working.txt";

    public static List<Map<String, String>> getDone(){
        return readFile(DONE);
    }

    public static List<Map<String, String>> getWorking(){
        return readFile(WORKING);
    }


    public static void writeFile(String path, Record record){
        File file1 = new File(path);
        try {
            FileWriter fw = new FileWriter(file1, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(record.toString()+"\n");
            bw.flush();
            bw.close();
            fw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static List<Map<String, String>> readFile(String path){
        ArrayList<Map<String, String>> dataGroup = null;
        try {
            FileReader fr = new FileReader(new File(path));
            BufferedReader br = new BufferedReader(fr);

            String readData;

            dataGroup = new ArrayList<>();

            while((readData = br.readLine())!=null){
                try{
                    String[] split = readData.split("==");
                    Map<String, String> map = new HashMap<>();
                    map.put("url", split[0]);
                    map.put("time", split[1]);
                    map.put("id", split[2]);
                    dataGroup.add(map);//读出所有数据，存入ArrayList中
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            br.close();
            fr.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return dataGroup;
    }



}
